//
//  TTSignInRecordNoViewController.m
//  Estate
//
//  Created by houzhen on 2018/9/5.
//  Copyright © 2018年 ttsx. All rights reserved.
//

#import "TTSignInRecordNoViewController.h"
#import "TTSignPeopleCell.h"
#import "TTProgressCell.h"

@interface TTSignInRecordNoViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(strong, nonatomic)UITableView *tableView;
/**监理数组*/
@property (nonatomic,strong) NSArray *jianliArr;
/**专监数组*/
@property (nonatomic,strong) NSArray *zhuanjianArr;

/**监理签到数组*/
@property (nonatomic,strong) NSMutableArray *jianliArrQian;
/**专监签到数组*/
@property (nonatomic,strong) NSMutableArray *zhuanjianArrQian;


/**未签到数组*/
@property (nonatomic,strong) NSMutableArray *dataArr;
/**签到数组*/
@property (nonatomic,strong) NSMutableArray *dataArrQian;

@property (nonatomic,assign) CGFloat f;
@end

@implementation TTSignInRecordNoViewController
-(UITableView *)tableView {
    if (_tableView == nil) {
        CGRect rect = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        _tableView = [[UITableView alloc] initWithFrame:rect];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1.00];
        [_tableView registerNib:[UINib nibWithNibName:@"TTSignPeopleCell" bundle:nil] forCellReuseIdentifier:@"TTSignPeopleCell"];
        _tableView.tableFooterView = [[UIView alloc]init];
        [_tableView registerClass:[TTProgressCell class] forCellReuseIdentifier:@"TTProgressCell"];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0,  self.view.frame.size.width, 40)];
        label.backgroundColor = RGBCOLOR(219/255.0, 238/255.0, 248/255.0);
        label.textColor = TTTheme.defaultManger.defaultColor;
        FMDatabase *db=[FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
        DBHelper *helper=[DBHelper help];
        NSDictionary *dataDic= [[helper DataBase:db
                                  selectKeyTypes:@{@"PROJECT_NAME":@"text"}
                                       fromTable:PROJECT whereCondition:@{@"ID":PROID}] firstObject];
        label.text = [NSString stringWithFormat:@"当前项目：%@",DEFISNUL(dataDic[@"PROJECT_NAME"])];
        label.font = [UIFont systemFontOfSize:16];
        label.numberOfLines = 0;
        CGFloat h =  [label.text boundingRectWithSize:CGSizeMake(DEF_SCREEN_WIDTH,MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin  attributes:@{NSFontAttributeName:label.font} context:nil].size.height + 10;
        if(h>40){
           label.frame = CGRectMake(0, 0,  self.view.frame.size.width, h);
        }
        label.textAlignment = NSTextAlignmentCenter;
        
        _tableView.tableHeaderView = label;
        
    }
    return _tableView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
   
    self.dataArrQian = [NSMutableArray array];
    self.dataArr = [NSMutableArray array];
    self.jianliArrQian  = [NSMutableArray array];
    self.zhuanjianArrQian = [NSMutableArray array];
    self.jianliArr = [LSUtility queryByType:@"USER_03"];

    if([USERROLE isEqualToString:@"USER_01"]){
        self.zhuanjianArr = [LSUtility queryByType:@"USER_07"];
        [self getqian:self.jianliArrQian withArr:self.jianliArr];
        [self getqian:self.zhuanjianArrQian withArr:self.zhuanjianArr];
        [self.dataArrQian addObjectsFromArray:self.zhuanjianArrQian];
        [self.dataArrQian addObjectsFromArray:self.jianliArrQian];
        
        for (NSDictionary *jianli in  self.jianliArr) {
            BOOL add = YES;
            for (NSDictionary *jianliqian in self.jianliArrQian) {
                if ([jianli[@"userid"] isEqualToString:jianliqian[@"userid"]]) {
                    add = NO;
                    break ;
                }
            }
            //未签到
            if (add) {
                [self.dataArr addObject:jianli];
            }
        }
        
        for (NSDictionary *jianli in  self.zhuanjianArr) {
            BOOL add = YES;
            for (NSDictionary *jianliqian in self.zhuanjianArrQian) {
                if ([jianli[@"userid"] isEqualToString:jianliqian[@"userid"]]) {
                    add = NO;
                    break ;
                }
            }
            //未签到
            if (add) {
                [self.dataArr addObject:jianli];
            }
        }
        
    }else{
        [self getqian:self.jianliArrQian withArr:self.jianliArr];
        //查询自己
        NSString *sqlStr = SQL_WORKRECORD_SELECT;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *name=[LSUtility getuserIdByUserName:USERID][@"REAL_NAME"];
        [dic setValue:DEFISNUL(USERID) forKey:@"userid"];
        [dic setValue:DEFISNUL(name) forKey:@"username"];
        if([self resultSetSql:sqlStr]){
            [self.dataArrQian addObject:dic];
        }else{
            [self.dataArr addObject:dic];
        }
        [self.dataArrQian addObjectsFromArray:self.jianliArrQian];
        
        for (NSDictionary *jianli in  self.jianliArr) {
            BOOL add = YES;
            for (NSDictionary *jianliqian in self.jianliArrQian) {
                if ([jianli[@"userid"] isEqualToString:jianliqian[@"userid"]]) {
                    add = NO;
                    break ;
                }
            }
            //未签到
            if (add) {
                [self.dataArr addObject:jianli];
            }
        }
        
    }
     self.f = self.dataArrQian.count*1.00/(self.dataArrQian.count+self.dataArr.count)*1.00;
    [self.view addSubview:self.tableView];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 80;
    [self.tableView reloadData];
   
}
-(void)getqian:(NSMutableArray *)qianarray withArr:(NSArray *)arr{
    for (NSMutableDictionary *dic in arr) {
        NSString *userid = dic[@"userid"];
        
        NSString *sqlStr = [NSString stringWithFormat:@"SELECT * FROM WORK_RECORD WHERE RECORD_TYPE IN('RECORD_05') AND PRO_ID='%@' AND RECORD_USER='%@' and STATE='1' and substr(CREATE_TIME,1,10)='%@' ORDER by CREATE_TIME DESC",PROID,userid,[LSUtility dateNow]];
        if ([self resultSetSql:sqlStr]) {
            [qianarray addObject:dic];
        }
    }
}
//查出数据
-(BOOL)resultSetSql:(NSString *)sql{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    FMResultSet *resultSet = [db executeQuery:sql];
    // 遍历结果
    while ([resultSet next]) {
        return YES;
    }
    return NO;
}

#pragma mark -UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 2){
        return 80;
    }else{
        return self.tableView.estimatedRowHeight;
    }
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 40)];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, DEF_SCREEN_WIDTH-20, 40)];
    if(section == 0){
       label.text = @" 今日已签到人员：";
    }else if (section == 1){
        label.text = @" 今日未签到人员：";
    }else{
        label.text = [NSString stringWithFormat:@" 今日出勤率：%.2f%%",self.f*100];
    }
    [view addSubview:label];
    return view;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        TTSignPeopleCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TTSignPeopleCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        NSString *str=@"";
        cell.contentLabel.font = [UIFont systemFontOfSize: 17*BIZ];
        for (NSDictionary *dic in self.dataArrQian) {
            str=[str stringByAppendingString:[NSString stringWithFormat:@"%@  ",dic[@"username"]]];
        }
        if([str isEqualToString:@""]){
            str = @"无";
        }
        cell.contentLabel.text = str;
        return cell;
    }else if (indexPath.section == 1){
        TTSignPeopleCell *cell=[tableView dequeueReusableCellWithIdentifier:@"TTSignPeopleCell" forIndexPath:indexPath];
        NSString *str=@"";
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.contentLabel.font = [UIFont systemFontOfSize: 18*BIZ];
        cell.contentLabel.textColor = [UIColor redColor];
        for (NSDictionary *dic in self.dataArr) {
            str=[str stringByAppendingString:[NSString stringWithFormat:@"%@  ",dic[@"username"]]];
        }
        if([str isEqualToString:@""]){
            str = @"无";
        }
        cell.contentLabel.text = str;
        return cell;
    }else{
        static NSString *rid = @"TTProgressCell";
        TTProgressCell *cell=[tableView dequeueReusableCellWithIdentifier:rid];
        if(cell==nil){
            cell=[[TTProgressCell alloc] initWithStyle:UITableViewCellStyleDefault      reuseIdentifier:rid];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.progressView.progress = self.f;

        return cell;
    }
    
}


/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
